<template>
  <div class="unanswered-questions">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>未解答问题</h2>
          <el-button 
            type="primary" 
            :icon="Upload"
            :loading="syncing"
            @click="handleSyncToKnowledgeBase"
          >
            同步高分答案到知识库
          </el-button>
        </div>
      </template>

      <el-table
        :data="questionList"
        v-loading="loading"
        stripe
        style="width: 100%"
        :row-style="{ height: '60px' }"
        :cell-style="{ padding: '16px 0' }"
        @expand-change="handleExpandChange"
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <div class="expand-content">
              <!-- 提交解答表单 -->
              <el-card class="answer-form-card">
                <template #header>
                  <span>提交人工解答</span>
                </template>
                <el-form @submit.prevent="handleSubmitAnswer(row.id)">
                  <el-form-item>
                    <el-input
                      v-model="answerInputs[row.id]"
                      type="textarea"
                      :rows="4"
                      placeholder="请输入您的解答..."
                    />
                  </el-form-item>
                  <el-form-item>
                    <el-button 
                      type="primary" 
                      @click="handleSubmitAnswer(row.id)"
                      :loading="submittingAnswers[row.id]"
                      :disabled="!answerInputs[row.id] || !answerInputs[row.id].trim()"
                    >
                      提交解答
                    </el-button>
                  </el-form-item>
                </el-form>
              </el-card>

              <!-- 已有解答列表 -->
              <el-card class="answers-list-card" v-if="expandedAnswers[row.id] && expandedAnswers[row.id].length > 0">
                <template #header>
                  <span>所有解答 ({{ expandedAnswers[row.id].length }})</span>
                </template>
                <div 
                  v-for="answer in expandedAnswers[row.id]" 
                  :key="answer.id"
                  class="answer-item"
                >
                  <div class="answer-content">
                    {{ answer.answer }}
                  </div>
                  <div class="answer-meta">
                    <span class="answer-time">{{ formatDate(answer.createdAt) }}</span>
                    <div class="answer-rating">
                      <el-button-group>
                        <el-button
                          :type="answer.rating === 'useful' ? 'success' : 'default'"
                          size="small"
                          @click="handleRate(answer.id, 'useful', row.id)"
                          :disabled="ratingAnswers[answer.id]"
                        >
                          <el-icon><Check /></el-icon>
                          有用 {{ answer.usefulCount || 0 }}
                        </el-button>
                        <el-button
                          :type="answer.rating === 'useless' ? 'danger' : 'default'"
                          size="small"
                          @click="handleRate(answer.id, 'useless', row.id)"
                          :disabled="ratingAnswers[answer.id]"
                        >
                          <el-icon><Close /></el-icon>
                          无用 {{ answer.uselessCount || 0 }}
                        </el-button>
                      </el-button-group>
                    </div>
                  </div>
                </div>
              </el-card>
              <el-card class="answers-list-card" v-else-if="row.answerCount === 0">
                <el-empty description="暂无解答" :image-size="80" />
              </el-card>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="userId" label="用户ID" width="100" />
        <el-table-column prop="question" label="问题" min-width="300" show-overflow-tooltip />
        <el-table-column prop="createdAt" label="提问时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.answerCount > 0 ? 'success' : 'warning'">
              {{ row.answerCount > 0 ? '已有解答' : '待解答' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="解答数" width="140" align="center">
          <template #default="{ row }">
            <div class="answer-count-cell">
              <el-badge 
                :value="row.answerCount || 0" 
                :max="99" 
                :type="row.answerCount > 0 ? 'primary' : 'info'"
                class="answer-badge"
              >
                <el-button 
                  size="small" 
                  :disabled="!row.answerCount || row.answerCount === 0"
                  @click="showAnswersDialog(row)"
                >
                  查看
                </el-button>
              </el-badge>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        style="margin-top: 20px; justify-content: center"
      />
    </el-card>

    <!-- 查看解答对话框 -->
    <el-dialog
      v-model="answersDialogVisible"
      :title="`问题：${currentQuestion?.question || ''}`"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-loading="loadingAnswers" class="answers-dialog-content">
        <div v-if="currentAnswers.length === 0" class="no-answers">
          <el-empty description="暂无解答" />
        </div>
        <div v-else class="answers-list">
          <div 
            v-for="answer in currentAnswers" 
            :key="answer.id"
            class="answer-card"
          >
            <div class="answer-header">
              <span class="answer-user">用户 ID: {{ answer.userId }}</span>
              <span class="answer-time">{{ formatDate(answer.createdAt) }}</span>
            </div>
            <div class="answer-body">
              {{ answer.answer }}
            </div>
            <div class="answer-footer">
              <div class="answer-stats">
                <el-tag type="success" size="small">
                  <el-icon><Check /></el-icon>
                  有用: {{ answer.usefulCount || 0 }}
                </el-tag>
                <el-tag type="danger" size="small">
                  <el-icon><Close /></el-icon>
                  无用: {{ answer.uselessCount || 0 }}
                </el-tag>
              </div>
              <div class="answer-actions">
                <el-button-group>
                  <el-button
                    size="small"
                    :type="answer.userRating === 'useful' ? 'success' : 'default'"
                    @click="handleRateInDialog(answer.id, 'useful')"
                    :disabled="ratingAnswers[answer.id]"
                  >
                    <el-icon><Check /></el-icon>
                    有用
                  </el-button>
                  <el-button
                    size="small"
                    :type="answer.userRating === 'useless' ? 'danger' : 'default'"
                    @click="handleRateInDialog(answer.id, 'useless')"
                    :disabled="ratingAnswers[answer.id]"
                  >
                    <el-icon><Close /></el-icon>
                    无用
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="answersDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Check, Close, Upload } from '@element-plus/icons-vue'
import { getUnansweredQuestions, submitAnswer, rateAnswer, getAnswers, syncToKnowledgeBase } from '../api/unanswered'
import { userStore } from '../store/user'

const questionList = ref([])
const loading = ref(false)
const syncing = ref(false)
const answerInputs = reactive({})
const submittingAnswers = reactive({})
const ratingAnswers = reactive({})
const expandedAnswers = reactive({}) // 存储展开行的解答数据

const pagination = ref({
  page: 1,
  size: 10,
  total: 0
})

// 查看解答对话框相关
const answersDialogVisible = ref(false)
const currentQuestion = ref(null)
const currentAnswers = ref([])
const loadingAnswers = ref(false)

const fetchQuestions = async () => {
  loading.value = true
  try {
    const response = await getUnansweredQuestions(pagination.value.page, pagination.value.size)
    questionList.value = response.records || response.content || []
    pagination.value.total = response.total || 0
  } catch (error) {
    ElMessage.error({
      message: error.message || '获取未解答问题失败，请稍后重试',
      duration: 3000
    })
    console.error('获取未解答问题失败:', error)
  } finally {
    loading.value = false
  }
}

// 显示解答对话框
const showAnswersDialog = async (question) => {
  currentQuestion.value = question
  answersDialogVisible.value = true
  loadingAnswers.value = true
  
  try {
    const answers = await getAnswers(question.id)
    currentAnswers.value = answers || []
  } catch (error) {
    ElMessage.error({
      message: error.message || '加载解答失败，请稍后重试',
      duration: 3000
    })
    console.error('加载解答失败:', error)
  } finally {
    loadingAnswers.value = false
  }
}

// 在对话框中评分
const handleRateInDialog = async (answerId, rating) => {
  ratingAnswers[answerId] = true
  try {
    await rateAnswer(answerId, rating, userStore.getCurrentUserId())
    ElMessage.success('评分成功')
    
    // 重新加载当前问题的解答
    if (currentQuestion.value) {
      const answers = await getAnswers(currentQuestion.value.id)
      currentAnswers.value = answers || []
    }
    
    // 同时刷新列表以更新解答数
    await fetchQuestions()
  } catch (error) {
    // 根据错误状态码显示不同的提示
    if (error.status === 429) {
      ElMessage.warning({
        message: error.message || '您今天已经对该解答评过分了，请明天再试',
        duration: 3000
      })
    } else {
      ElMessage.error({
        message: error.message || '评分失败，请稍后重试',
        duration: 3000
      })
    }
    console.error('评分失败:', error)
  } finally {
    ratingAnswers[answerId] = false
  }
}

// 处理展开行变化
const handleExpandChange = async (row, expandedRows) => {
  // 如果行被展开且还没有加载解答数据
  if (expandedRows.some(r => r.id === row.id) && !expandedAnswers[row.id]) {
    try {
      const answers = await getAnswers(row.id)
      expandedAnswers[row.id] = answers || []
    } catch (error) {
      console.error(`加载问题${row.id}的解答失败:`, error)
      ElMessage.error({
        message: error.message || '加载解答失败，请稍后重试',
        duration: 3000
      })
    }
  }
}

const handleSubmitAnswer = async (questionId) => {
  const answer = answerInputs[questionId]
  if (!answer || !answer.trim()) {
    ElMessage.warning('请输入解答内容')
    return
  }

  submittingAnswers[questionId] = true
  try {
    await submitAnswer(questionId, answer, userStore.getCurrentUserId())
    ElMessage.success('提交解答成功')
    answerInputs[questionId] = ''
    
    // 重新加载该问题的解答
    const answers = await getAnswers(questionId)
    expandedAnswers[questionId] = answers || []
    
    // 刷新列表以更新解答数
    await fetchQuestions()
  } catch (error) {
    ElMessage.error({
      message: error.message || '提交解答失败，请稍后重试',
      duration: 3000
    })
    console.error('提交解答失败:', error)
  } finally {
    submittingAnswers[questionId] = false
  }
}

// 在展开行中评分
const handleRate = async (answerId, rating, questionId) => {
  ratingAnswers[answerId] = true
  try {
    await rateAnswer(answerId, rating, userStore.getCurrentUserId())
    ElMessage.success('评分成功')
    
    // 重新加载该问题的解答
    const answers = await getAnswers(questionId)
    expandedAnswers[questionId] = answers || []
    
    // 刷新列表以更新解答数
    await fetchQuestions()
  } catch (error) {
    // 根据错误状态码显示不同的提示
    if (error.status === 429) {
      ElMessage.warning({
        message: error.message || '您今天已经对该解答评过分了，请明天再试',
        duration: 3000
      })
    } else {
      ElMessage.error({
        message: error.message || '评分失败，请稍后重试',
        duration: 3000
      })
    }
    console.error('评分失败:', error)
  } finally {
    ratingAnswers[answerId] = false
  }
}

const handlePageChange = (page) => {
  pagination.value.page = page
  fetchQuestions()
}

const handleSizeChange = (size) => {
  pagination.value.size = size
  pagination.value.page = 1
  fetchQuestions()
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 手动触发同步高分答案到知识库
const handleSyncToKnowledgeBase = async () => {
  try {
    await ElMessageBox.confirm(
      '此操作将把所有高分答案同步到Dify知识库，是否继续？',
      '确认同步',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    syncing.value = true
    
    const result = await syncToKnowledgeBase()
    
    if (result.success) {
      ElMessage.success({
        message: `同步完成！成功：${result.syncedCount}，失败：${result.failedCount}，总计：${result.totalCount}`,
        duration: 5000
      })
      
      // 刷新列表
      await fetchQuestions()
    } else {
      ElMessage.error({
        message: result.error || '同步失败',
        duration: 3000
      })
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error({
        message: error.message || '同步失败，请稍后重试',
        duration: 3000
      })
      console.error('同步失败:', error)
    }
  } finally {
    syncing.value = false
  }
}

onMounted(() => {
  fetchQuestions()
})
</script>

<style scoped>
.unanswered-questions {
  max-width: 1400px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
}

.expand-content {
  padding: 24px;
  background: linear-gradient(135deg, #f6f8fb 0%, #f0f2f5 100%);
  border-radius: 8px;
}

.answer-form-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.answers-list-card {
  margin-top: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.answer-item {
  padding: 16px;
  background-color: white;
  border-radius: 6px;
  margin-bottom: 12px;
  border-left: 3px solid #1890ff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);
  transition: all 0.3s;
}

.answer-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transform: translateX(2px);
}

.answer-item:last-child {
  margin-bottom: 0;
}

.answer-content {
  line-height: 1.8;
  margin-bottom: 12px;
  white-space: pre-wrap;
  word-wrap: break-word;
  color: #262626;
  font-size: 14px;
}

.answer-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #8c8c8c;
  font-size: 13px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.answer-time {
  font-size: 12px;
}

.answer-rating {
  display: flex;
  gap: 8px;
}

/* 解答对话框样式 */
.answers-dialog-content {
  min-height: 200px;
  max-height: 600px;
  overflow-y: auto;
}

.no-answers {
  padding: 40px 0;
  text-align: center;
}

.answers-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.answer-card {
  background: linear-gradient(135deg, #f6f8fb 0%, #ffffff 100%);
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 16px;
  transition: all 0.3s;
}

.answer-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border-color: #1890ff;
}

.answer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.answer-user {
  font-weight: 500;
  color: #1890ff;
  font-size: 13px;
}

.answer-time {
  color: #8c8c8c;
  font-size: 12px;
}

.answer-body {
  line-height: 1.8;
  color: #262626;
  font-size: 14px;
  white-space: pre-wrap;
  word-wrap: break-word;
  margin-bottom: 12px;
  padding: 12px;
  background: white;
  border-radius: 4px;
}

.answer-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.answer-stats {
  display: flex;
  gap: 8px;
}

.answer-actions {
  display: flex;
  gap: 8px;
}

/* 表格行间距调整 */
:deep(.el-table__row) {
  height: 60px;
}

:deep(.el-table td.el-table__cell) {
  padding: 16px 0;
}

/* 解答数列样式 */
.answer-count-cell {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 40px;
}

.answer-badge {
  display: inline-flex;
  align-items: center;
}

:deep(.answer-badge .el-badge__content) {
  transform: translateY(-50%) translateX(100%);
  top: 8px;
  right: 8px;
  height: 20px;
  line-height: 20px;
  padding: 0 6px;
  min-width: 20px;
  font-size: 12px;
  font-weight: 500;
}
</style>
